package com.happystudy.controller;

import com.happpystudy.model.User;
import com.happpystudy.model.course.*;
import com.happpystudy.model.courseItem.CourseTopicItem;
import com.happpystudy.model.courseItem.SubmitRecord;
import com.happpystudy.model.grade.CourseFile;
import com.happpystudy.model.grade.Grade;
import com.happpystudy.service.*;
import com.happystudy.message.*;

import com.happystudy.serviceImpl.CourseScheduleKeyServiceImpl;
import com.happystudy.tools.TaskInfo;
import com.happystudy.tools.UserToGradeMapper;
import com.happystudy.util.KeyUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CourseController {

    @Resource
    CourseFileService courseFileService;

    @Resource
    CourseService courseService;

    @Resource
    GradeService gradeService;
    @Resource
    CourseTopicItemService courseTopicItemService;

    @Resource
    CourseScheduleKeyServiceImpl courseScheduleKeyService;

    @Resource
    CourseTopicService courseTopicService;


    @Resource
    UserService userService;

    @Resource
    SubmitRecordService submitRecordService;

    @Resource
    CourseJoinStudentService courseJoinStudentService;

    @Resource
    FileService fileService;
    /**
     * @param request 请求体
     * @return 返回加入course页面
     */
    @GetMapping("/course/createCourse")
    public String returnCreateCourseHTML(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null){
            System.out.println("未登录");
            return "login";
        }
        User currentUser = (User) session.getAttribute("currentLoginUser");
        if (currentUser==null){
            System.out.println("有session，但是没有登录信息");
            return "login";
        }
        return "createCourse";
    }
    @GetMapping("/update/psw")
    public String returnPSWHTML(){
        return  "uploadePSW.html";

    }

    @GetMapping("/course/joinCourse")
    public String returnJoinCourseHTML(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null){
            System.out.println("未登录");
            return "login";
        }
        User currentUser = (User) session.getAttribute("currentLoginUser");
        if (currentUser==null){
            System.out.println("有session，但是没有登录信息");
            return "login";
        }
        return "joinCourse";
    }


    @GetMapping("/course/isCourseExists")
    @ResponseBody
    public BaseMessageModel isCourseExists(CourseKey courseKey){
        Course course = courseService.queryCourseByCourseKey(courseKey);
        BaseMessageModel message;
        if (course!=null){
            message = new ErrorMessage(ErrorMessageType.CURRENT_COURSE_HAD_EXISTS_CODE,ErrorMessageType.CURRENT_COURSE_HAD_EXISTS_MSG);
        }else {
            message =  new SuccessMessage();
        }
        return message;
    }

    @PostMapping("/course/doCreateCourse")
    @ResponseBody
    public BaseMessageModel createCourse(@RequestBody Course course,HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null){
            return new ErrorMessage(ErrorMessageType.USER_NOT_LOGIN_CODE,ErrorMessageType.USER_NOT_LOGIN_MSG);
        }
        System.out.println(course);
        String sessionKey =KeyUtil.SESSION_CURRENT_USER_KEY;
        int result = courseService.doCreateCourse(course);
        if (result>0){
            User user = userService.returnUserInfoByUserID(course.getUserId());
            System.out.println("查询结果："+user.toString());
            session.setAttribute(sessionKey,user);
            //返回courseboard
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.CREATE_COURSE_ERROR_CODE,ErrorMessageType.CREATE_COURSE_ERROR_MSG);
        }
    }


    /**
     * 加入课程
     * @param course 加入的课程信息
     * @param request 请求体
     * @return
     */
    @PostMapping("/course/doJoinCourse")
    @ResponseBody
    public BaseMessageModel joinCourse(Course course,HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null){
            return new ErrorMessage(ErrorMessageType.USER_NOT_LOGIN_CODE,ErrorMessageType.USER_NOT_LOGIN_MSG);
        }
        int result = courseService.doJoinCourse(course);
        if (result==-1){
            return new ErrorMessage(ErrorMessageType.COURSE_NOT_EXIST_CODE,ErrorMessageType.COURSE_NOT_EXIST_MSG);
        }else if (result==-2){
            return new ErrorMessage(ErrorMessageType.WRONG_COURSE_CODE,ErrorMessageType.WRONG_COURSE_MSG);
        }else if (result==-3){
            return new ErrorMessage(ErrorMessageType.REJOIN_COURSE_CODE,ErrorMessageType.REJOIN_COURSE_MSG);
        }else {
            User user = userService.returnUserInfoByUserID(course.getUserId());
            String sessionKey = KeyUtil.SESSION_CURRENT_USER_KEY;
            session.setAttribute(sessionKey,user);
            System.out.println("我是user"+user);
            return new LocationMessage("/courseBordStudent");
        }

    }

    @GetMapping("/course/createItem")
    @ResponseBody
    public BaseMessageModel returnCreateTopicItemHTML(CourseTopic courseTopic, HttpServletRequest request){
        System.out.println(courseTopic);
        HttpSession session = request.getSession(false);

        return new LocationMessage(
                "success",
                true,
                ErrorMessageType.SUCCESS_CODE,
                "",
                "/createCourseItem/"+KeyUtil.returnCrouseKeyPath(courseTopic)
        );

    }

    @PostMapping("/course/doCreateCourseTopicItem")
    @ResponseBody
    public BaseMessageModel doCreateCourseTopicItem(CourseTopicItem courseTopicItem, MultipartFile file){
        System.out.println(courseTopicItem);
        int result = courseTopicItemService.doCreateCourseTopicItem(courseTopicItem,file);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.INSERT_DATA_FAIL_CODE,ErrorMessageType.INSERT_DATA_FEIL_MSG);
        }
    }

    @GetMapping("/course/loadCourseTopicBar/{uniId}/{courseId}/{courseGroup}")
    @ResponseBody
    public BaseMessageModel loadCourseTopicBar(@PathVariable(value = "courseId") String courseId,
                                               @PathVariable(value = "uniId") String uniId,
                                               @PathVariable(value = "courseGroup") Integer courseGroup){
        List<CourseTopic> courseTopics = courseTopicService.queryAllCourseTopicByCourseKey(uniId, courseId, courseGroup);
        System.out.println(courseTopics);
        for (CourseTopic courseTopic:courseTopics){
            Integer topicId = courseTopic.getTopicId();
            List<CourseTopicItem> courseTopicItems = courseTopicItemService.queryAllCourseTopicItemByTopicId(topicId);
            System.out.println(courseTopicItems);
            courseTopic.setCourseTopicItems(courseTopicItems);
        }

        return new SingleDataMessage(courseTopics);
    }
    @GetMapping("/course/participants/{uniId}/{courseId}/{courseGroup}")
    public String returnParticipantsHTML(Model model,
                                         @PathVariable(value = "courseId") String courseId,
                                         @PathVariable(value = "uniId") String uniId,
                                         @PathVariable(value = "courseGroup") Integer courseGroup){
        CourseKey courseKey = new CourseKey();
        courseKey.setUniId(uniId);
        courseKey.setCourseId(courseId);
        courseKey.setCourseGroup(courseGroup);
        List<User> users = courseService.queryAllUserByCourseKey(courseKey);
        model.addAttribute("users",users);
        model.addAttribute("courseId",courseId);
        model.addAttribute("courseGroup",courseGroup);
        return "participants";
    }

    @PostMapping("/course/uploadFile")
    @ResponseBody
    public BaseMessageModel uploadSubmitRecord(SubmitRecord submitRecord,MultipartFile file){
        System.out.println(submitRecord);
        System.out.println(file);
        int result = submitRecordService.doStudentUploadFile(submitRecord, file);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }

    }

    @PostMapping("/course/updateFile")
    @ResponseBody
    public BaseMessageModel updateSubmitRecord(SubmitRecord submitRecord,MultipartFile file){


        int result = submitRecordService.doStudentUploadFile(submitRecord, file);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }

    }

    @PostMapping("/course/deleteFile")
    @ResponseBody
    public BaseMessageModel deleteSubmitRecord(Integer itemId){


        int result = submitRecordService.deleteSubmitRecord(itemId);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }

    }


    @GetMapping("/course/itemInfo/{itemId}/{courseGroup}/{courseId}")
    public String returnItemInfoHTML(
            @PathVariable(value = "itemId") Integer itemId,
            @PathVariable(value = "courseGroup") Integer courseGroup,
            @PathVariable(value = "courseId") String courseId,
            HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null){
            return "login";
        }
        String flag="Unsubmitted";
        System.out.println();
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(itemId);
        List<SubmitRecord> submitRecords = submitRecordService.selectAllSubmitRecordByItemId(itemId);



        SubmitRecord currentSubmitRecord = new SubmitRecord();
        if ("TASK".equalsIgnoreCase(courseTopicItem.getItemType()) && submitRecords.size()!=0) {
            currentSubmitRecord = submitRecords.get(0);
            for (int i = 1; i < submitRecords.size(); i++) {
                if (submitRecords.get(i).getUploadTime().after(currentSubmitRecord.getUploadTime())) {
                    currentSubmitRecord = submitRecords.get(i);
                }
            }

            if (currentSubmitRecord.getUploadTime().after(courseTopicItem.getItemDue())){
                flag="Late";
            }else {
                flag="Submitted";
            }
        }

        model.addAttribute("courseId",courseId);
        model.addAttribute("courseGroup",courseGroup);
        model.addAttribute("user",user);
        model.addAttribute("submitRecord",currentSubmitRecord);
        model.addAttribute("courseTopicItem",courseTopicItem);
        model.addAttribute("flag",flag);
        return "itemInfo";
    }

    @GetMapping("/course/download")
    public ResponseEntity<InputStream> downloadFail(String addr, String name, String contentType, HttpServletResponse response){
        System.out.println(addr);
        System.out.println(name);
        byte[] bytes = fileService.doDownload(addr);
        response.setContentType(contentType);
        try {
            name = new String(name.getBytes(), "ISO_8859_1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addHeader("Content-Disposition","filename="+name);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("/gradesInfo/{uniId}/{courseId}/{courseGroup}")
    public String returnGradesInfo(Model model,
                                   @PathVariable(value = "uniId") String uniId,
                                   @PathVariable(value = "courseId") String cuourseId,
                                   @PathVariable(value = "courseGroup") Integer courseGroup) {

        CourseTopic course = new CourseTopic();
        course.setCourseId(cuourseId);
        course.setUniId(uniId);
        List<CourseTopic> courseTopics = courseTopicService.queryAllCourseTopicByCourseKey(uniId,cuourseId,courseGroup);
        List<CourseTopicItem> taskList = new ArrayList<>();
        List<CourseTopicItem> testList = new ArrayList<>();
        if (courseTopics.size()!=0){
            for (CourseTopic courseTopic:courseTopics){
                List<CourseTopicItem> courseTopicItems = courseTopicItemService.queryAllCourseTopicItemByTopicId(courseTopic.getTopicId());
                for (CourseTopicItem courseTopicItem:courseTopicItems){
                    if ("TASK".equalsIgnoreCase(courseTopicItem.getItemType())){
                        taskList.add(courseTopicItem);
                    }else if ("TEST".equalsIgnoreCase(courseTopicItem.getItemType())){
                        testList.add(courseTopicItem);
                    }
                }
            }

        }

        System.out.println(courseTopics);
        model.addAttribute("testList",testList);
        model.addAttribute("taskList",taskList);
        model.addAttribute("uniId",uniId);
        model.addAttribute("courseId",cuourseId);
        model.addAttribute("courseGroup",courseGroup);
        return "gradeInfo";
    }



    @GetMapping("/grade/{uniId}/{courseId}/{courseGroup}/{topicId}/{itemId}")
    public String reutrnGradeHTML(Model model,
                                  @PathVariable(value = "uniId") String uniId,
                                  @PathVariable(value = "courseId") String courseId,
                                  @PathVariable(value = "courseGroup") Integer courseGroup,
                                  @PathVariable(value = "topicId") Integer topicId,
                                  @PathVariable(value = "itemId") Integer itemId){

        Course course = new Course();
        course.setUniId(uniId);
        course.setCourseId(courseId);
        course.setCourseGroup(courseGroup);
        List<User> users = courseJoinStudentService.selectAllUserByCourseKey(course);
        CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(itemId);
        List<UserToGradeMapper> list = new ArrayList<>();
        for (User user:users){
            if ("TASK".equalsIgnoreCase(courseTopicItem.getItemType())){
                SubmitRecord submitRecord = new SubmitRecord();
                submitRecord.setUserId(user.getUserId());
                submitRecord.setItemId(itemId);
                submitRecord.setCourseId(courseId);
                submitRecord.setUniId(uniId);
                submitRecord.setCourseGroup(courseGroup);
                SubmitRecord submitRecord1 = submitRecordService.selectByCourseInfo(submitRecord);
                if (submitRecord1!=null){
                    if (submitRecord1.getUploadTime().after(courseTopicItem.getItemDue())){
                        user.setFlag("Late");
                    }else {
                        user.setFlag("Submitted");
                    }
                    user.setSubmitRecord(submitRecord);
                }else {
                    user.setFlag("UnSubmitted");
                }
            }

            Grade grade = new Grade();
            grade.setUserId(user.getUserId());
            grade.setUniId(uniId);
            grade.setCourseId(courseId);
            grade.setCourseGroup(courseGroup);
            grade.setTopicId(topicId);
            grade.setItemId(itemId);
            Grade selectedGrade = gradeService.queryGradeByKey(grade);
            if (selectedGrade!=null && selectedGrade.getGrade()!=null){
                list.add(new UserToGradeMapper(user,selectedGrade.getGrade().toString()));

            }else {

                list.add(new UserToGradeMapper(user,""));
            }
            if (selectedGrade==null){
                gradeService.insertGrade(grade);
            }
        }
        model.addAttribute("topicItem",courseTopicItem);
        model.addAttribute("itemType",courseTopicItem.getItemType());
        model.addAttribute("list",list);
        model.addAttribute("uniId",uniId);
        model.addAttribute("courseId",courseId);
        model.addAttribute("courseGroup",courseGroup);
        model.addAttribute("topicId",topicId);
        model.addAttribute("itemId",itemId);
        return "doGrade";
    }

    @GetMapping("/grade/{userId}/{uniId}/{courseId}/{courseGroup}/{topicId}/{itemId}")
    public String returnSubmitInfoHTML(Model model,
                                       @PathVariable(value = "userId") Integer userId,
                                       @PathVariable(value = "uniId") String uniId,
                                       @PathVariable(value = "courseId") String courseId,
                                       @PathVariable(value = "courseGroup") Integer courseGroup,
                                       @PathVariable(value = "topicId") Integer topicId,
                                       @PathVariable(value = "itemId") Integer itemId){
        User user = userService.returnUserInfoByUserID(userId);
        List<SubmitRecord> submitRecords = submitRecordService.selectAllSubmitRecordByItemId(itemId);
        CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(itemId);

        model.addAttribute("user",user);
        model.addAttribute("submitRecords",submitRecords);
        model.addAttribute("courseId",courseId);
        model.addAttribute("courseGroup",courseGroup);
        model.addAttribute("topicItem",courseTopicItem);
        model.addAttribute("itemType",courseTopicItem.getItemType());
        return "submitInfo";

    }


    @PostMapping("/grade/updateGrade")
    @ResponseBody
    public BaseMessageModel updateGrades(@RequestBody  List<Grade> grades){
        for (Grade grade:grades){
            int i = gradeService.doUpdateGrade(grade);
        }
        return new SuccessMessage();
    }

    @GetMapping("/timetable")
    public String returnTimeTableHTML(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }

        return "timeTable";
    }

    @GetMapping("/timetable/schedule")
    public String returnScheduleHTML(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }

        return "schedule";
    }

    @GetMapping("/getTime/{userId}")
    @ResponseBody
    public BaseMessageModel getTimeTable(@PathVariable("userId") Integer userId){
        List<Course> list = new ArrayList<>();
        List<CourseTeacher> courses = courseService.queryCoursesByUserId(userId, "learner");
        for (CourseTeacher courseTeacher:courses){
            CourseKey courseKey = new CourseKey();
            courseKey.setUniId(courseTeacher.getUniId());
            courseKey.setCourseGroup(courseTeacher.getCourseGroup());
            courseKey.setCourseId(courseTeacher.getCourseId());

            List<Course> courses1 = courseService.queryCourseByCourseId(courseKey);
            if (courses1.size()!=0){
                List<CourseScheduleKey> courseScheduleKeys = courseScheduleKeyService.queryAllScheduleByCourseKey(courseKey);
                Course currentCourse = courses1.get(0);
                currentCourse.setTimeList(courseScheduleKeys);
                list.add(currentCourse);
            }
        }
        return new SingleDataMessage(list);
    }

    @GetMapping("/timetable/getTaskGrade")
    public String getTaskGrade(HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }
        List<TaskInfo> tasks = new ArrayList<>();
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        List<CourseTeacher> courses = courseJoinStudentService.queryAllCourseJoinStudentByUserId(user.getUserId());
        System.out.println(tasks);
        if (courses.size()!=0){
            for (CourseTeacher course:courses){
                List<CourseTopic> courseTopics = courseTopicService.queryAllCourseTopicByCourseKey(course.getUniId(), course.getCourseId(), course.getCourseGroup());
                if (courseTopics.size()!=0){
                    for (CourseTopic courseTopic:courseTopics){
                        List<CourseTopicItem> courseTopicItems = courseTopicItemService.queryAllCourseTopicItemByTopicId(courseTopic.getTopicId());
                        if (courseTopicItems.size()!=0){
                            for (CourseTopicItem topicItem:courseTopicItems){
                                if ("TASK".equalsIgnoreCase(topicItem.getItemType())){
                                    tasks.add(new TaskInfo(course.getCourseId(),topicItem.getItemTitle(),topicItem.getItemId(),topicItem.getItemDue()));
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println(tasks);
//        List<Grade> allGradeByUserId = gradeService.getAllGradeByUserId(user.getUserId());
//        if (allGradeByUserId.size()!=0){
//            for (Grade grade:allGradeByUserId){
//                CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(grade.getItemId());
//                System.out.println(courseTopicItem);
//
//            }
//        }
        model.addAttribute("list",tasks);
        return "getTaskGrade";
    }

    @GetMapping("/timetable/getTestGrade")
    public String getTestGrade(HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }
        List<TaskInfo> tasks = new ArrayList<>();
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        List<CourseTeacher> courses = courseJoinStudentService.queryAllCourseJoinStudentByUserId(user.getUserId());
        System.out.println(tasks);
        if (courses.size()!=0){
            for (CourseTeacher course:courses){
                List<CourseTopic> courseTopics = courseTopicService.queryAllCourseTopicByCourseKey(course.getUniId(), course.getCourseId(), course.getCourseGroup());
                if (courseTopics.size()!=0){
                    for (CourseTopic courseTopic:courseTopics){
                        List<CourseTopicItem> courseTopicItems = courseTopicItemService.queryAllCourseTopicItemByTopicId(courseTopic.getTopicId());
                        if (courseTopicItems.size()!=0){
                            for (CourseTopicItem topicItem:courseTopicItems){
                                if ("TEST".equalsIgnoreCase(topicItem.getItemType())){
                                    tasks.add(new TaskInfo(course.getCourseId(),topicItem.getItemTitle(),topicItem.getItemId(),topicItem.getItemFrom(),topicItem.getItemTo()));
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println(tasks);
//        List<Grade> allGradeByUserId = gradeService.getAllGradeByUserId(user.getUserId());
//        if (allGradeByUserId.size()!=0){
//            for (Grade grade:allGradeByUserId){
//                CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(grade.getItemId());
//                System.out.println(courseTopicItem);
//
//            }
//        }
        model.addAttribute("list",tasks);
        return "getTestGrade";
    }

    @GetMapping("/grade")
    public String returnGradeHTML(HttpServletRequest request,Model model){


        return "gradeBar";
    }




    @GetMapping("/grade/taskSources")
    public String getTaskSources(HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }
        List<CourseTopicItem> items = new ArrayList<>();
        List<Grade> grades = new ArrayList<>();
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        List<Grade> allGradeByUserId = gradeService.getAllGradeByUserId(user.getUserId());
        if (allGradeByUserId.size()!=0){
            for (Grade grade:allGradeByUserId){
                CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(grade.getItemId());
                if (courseTopicItem!=null && "TASK".equalsIgnoreCase(courseTopicItem.getItemType())){
                    grades.add(grade);
                    items.add(courseTopicItem);
                }

            }
        }
        model.addAttribute("list",grades);
        model.addAttribute("items",items);
        return "taskSources";
    }

    @GetMapping("/grade/testSources")
    public String getTestSources(HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }
        List<CourseTopicItem> items = new ArrayList<>();
        List<Grade> grades = new ArrayList<>();
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        List<Grade> allGradeByUserId = gradeService.getAllGradeByUserId(user.getUserId());
        if (allGradeByUserId.size()!=0){
            for (Grade grade:allGradeByUserId){
                CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(grade.getItemId());
                if (courseTopicItem!=null && "TEST".equalsIgnoreCase(courseTopicItem.getItemType())){
                    grades.add(grade);
                    items.add(courseTopicItem);
                }

            }
        }
        model.addAttribute("list",grades);
        model.addAttribute("items",items);
        return "testSources";
    }

    @GetMapping("/drive")
    public String returnDriveHTML(HttpServletRequest request,Model model){
        HttpSession session = request.getSession(false);
        if (session==null) {
            return "login";
        }
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);

        List<CourseTeacher> courses = courseService.queryCoursesByUserId(user.getUserId(), user.getRole());

        model.addAttribute("courses",courses);
        model.addAttribute("user",user);
        return "drive";
    }
    
    @PostMapping("/driver/upload")
    @ResponseBody
    public BaseMessageModel uploadCourseFile(CourseFile courseFile, MultipartFile file){
        System.out.println(courseFile);
        try {
            String fullPath = fileService.doSave(file);
            System.out.println(fullPath);
            courseFile.setUuid(fullPath);
            courseFile.setAttachment(file.getOriginalFilename());
            courseFile.setUploadTime(new Date());
            courseFile.setContentType(file.getContentType());
            int result = courseFileService.insertCourseFile(courseFile);
            if (result>0){
                return new SuccessMessage();
            }else {
                return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }
    }


    @PostMapping("/driver/query")
    @ResponseBody
    public BaseMessageModel queryCourseFile(CourseKey courseKey){
        List<CourseFile> files = courseFileService.selectAllCourseFilesByCourseKey(courseKey);
        return new SingleDataMessage(files);
    }

    @PostMapping("/driver/delete")
    @ResponseBody
    public BaseMessageModel deleteCourseFile(String fullPath){
        int result = courseFileService.deleteCourseFile(fullPath);
        if(result>0){
            return new SuccessMessage();
        }
        return new ErrorMessage(16,"delete fail!");
    }

    @DeleteMapping("/topicId/delete")
    @ResponseBody
    public BaseMessageModel deleteTopicItem(Integer itemId){
        int result = courseTopicItemService.deleteCourseItemByKey(itemId);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }
    }


    @DeleteMapping("/topic/delete")
    @ResponseBody
    public BaseMessageModel deleteTopic(Integer topicId){
        int result = courseTopicService.deleteByPK(topicId);
        int result1 = courseTopicItemService.deleteByTopicId(topicId);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.UPLOAD_FAIL_CODE,ErrorMessageType.UPLOAD_FAIL_MSG);
        }
    }

    @GetMapping("/updateItem/{itemId}/{uniId}/{courseId}/{topicId}")
    public String updateItem(Model model,
                             @PathVariable("itemId") Integer itemId,
                             @PathVariable("uniId") String uniId,
                             @PathVariable("courseId") String courseId,
                             @PathVariable("topicId") Integer topicId){
        CourseTopicItem courseTopicItem = courseTopicItemService.queryCourseTopicItemByItemId(itemId);
        CourseTopic courseTopic = courseTopicService.queryCourseTopicByParimaryKey(topicId);
        model.addAttribute("item",courseTopicItem);
        model.addAttribute("uniId",uniId);
        model.addAttribute("courseId",courseId);
        model.addAttribute("currentTopic",courseTopic);
        return "updateTopicItem";
    }

    @PostMapping("/update/courseItem")
    @ResponseBody
    public BaseMessageModel doUpdateCourseTopicItem(CourseTopicItem courseTopicItem, MultipartFile file){
        System.out.println(courseTopicItem);
        int result = courseTopicItemService.doUpdateCourseTopicItem(courseTopicItem,file);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(ErrorMessageType.INSERT_DATA_FAIL_CODE,ErrorMessageType.INSERT_DATA_FEIL_MSG);
        }
    }


    @PostMapping("/changePSW")
    @ResponseBody
    public BaseMessageModel changepassword(String password,HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(KeyUtil.SESSION_CURRENT_USER_KEY);
        user.setPasswords(password);
        int result = userService.changgepassword(user);
        if (result>0){
            return new SuccessMessage();
        }else {
            return new ErrorMessage(20,"fail");
        }

    }


}
